package com.hua.designpattern.structural.composite;

/**
 * 
 * @author joshua
 * 
 *         <pre>
 *         
 *  组合模式是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象，用来表示部分以及整体层次。
 * 
 *  优点： 1、高层模块调用简单。 2、节点自由增加。 
 *  缺点：在使用组合模式时，其叶子和树枝的声明都是实现类，而不是接口，违反了依赖倒置原则。
 *  
 *    REF:
 *        在 JAVA AWT 和 SWING 中，对于 Button 和 Checkbox 是树叶，Container 是树枝
 * 
 *         </pre>
 */
public class TestComposite {

	public static void main(String[] args) {
		BaseObject root = new BaseObject("root", "0");
		BaseObject ob1 = new BaseObject("ob1", "1");
		BaseObject ob2 = new BaseObject("ob2", "2");
		BaseObject ob3 = new BaseObject("ob3", "3");
		BaseObject ob11 = new BaseObject("ob11", "11");
		BaseObject ob12 = new BaseObject("ob12", "12");
		BaseObject ob13 = new BaseObject("ob13", "13");
		BaseObject ob31 = new BaseObject("ob31", "31");
		BaseObject ob32 = new BaseObject("ob32", "32");
		BaseObject ob311 = new BaseObject("ob312", "311");
		BaseObject ob312 = new BaseObject("ob312", "312");
		root.addChild(ob1);
		root.addChild(ob2);
		root.addChild(ob3);
		ob1.addChild(ob11);
		ob1.addChild(ob12);
		ob1.addChild(ob13);
		ob3.addChild(ob31);
		ob3.addChild(ob32);
		ob31.addChild(ob311);
		ob31.addChild(ob312);

		display(root);
		System.out.println("--------");
		displayTree(root, "    ");
	}

	private static void display(BaseObject object) {
		System.out.println(object);
		if (object.getChildren() != null) {
			for (BaseObject child : object.getChildren()) {
				display(child);
			}
		}
	}

	private static void displayTree(BaseObject object, String blanks) {
		System.out.println(blanks + object.getName() + " " + object.getLevel());
		if (object.getChildren() != null) {
			for (BaseObject child : object.getChildren()) {
				displayTree(child, blanks + "        ");
			}
		}
	}

}
